package api

import (
	"strconv"

	"github.com/gin-gonic/gin"

	bookApp "BookStack/internal/application/book"
	"BookStack/internal/interfaces/middleware"
	"BookStack/internal/interfaces/presenter"
)

// BookRecycleHandler 书籍回收站API处理器
type BookRecycleHandler struct {
	bookService bookApp.ApplicationService
	response    presenter.ResponseFormatter
}

// NewBookRecycleHandler 创建书籍回收站API处理器
func NewBookRecycleHandler(bookService bookApp.ApplicationService) *BookRecycleHandler {
	return &BookRecycleHandler{
		bookService: bookService,
		response:    presenter.NewResponseFormatter(),
	}
}

// RegisterRoutes 注册书籍回收站相关路由
func (h *BookRecycleHandler) RegisterRoutes(r *gin.RouterGroup) {
	// 所有回收站操作都需要管理员权限
	admin := r.Group("/admin/book/recycle")
	admin.Use(middleware.JWTAuth(), middleware.AdminAuth()) // 管理员权限认证中间件
	{
		admin.GET("", h.ListRecycleBin)
		admin.POST("/book/:id/restore", h.RestoreBook)
		admin.POST("/chapter/:id/restore", h.RestoreChapter)
		admin.POST("/batch-restore", h.BatchRestore)
		admin.DELETE("/permanent-delete", h.PermanentlyDelete)
		admin.DELETE("/clear", h.ClearRecycleBin)
	}
}

// ListRecycleBin 获取回收站列表
func (h *BookRecycleHandler) ListRecycleBin(c *gin.Context) {
	var params bookApp.RecycleBinQueryParams
	if err := c.ShouldBindQuery(&params); err != nil {
		c.Error(err)
		return
	}

	// 设置默认值
	if params.Page <= 0 {
		params.Page = 1
	}
	if params.PageSize <= 0 || params.PageSize > 100 {
		params.PageSize = 20
	}

	resp, err := h.bookService.ListRecycleBin(c, &params)
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, resp)
}

// RestoreBook 恢复被删除的书籍
func (h *BookRecycleHandler) RestoreBook(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.Error(bookApp.ValidationError("id", "无效的书籍ID"))
		return
	}

	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	if err := h.bookService.RestoreBookFromRecycleBin(c, uint(id), userID); err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, gin.H{"message": "书籍已成功恢复"})
}

// RestoreChapter 恢复被删除的章节
func (h *BookRecycleHandler) RestoreChapter(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.Error(bookApp.ValidationError("id", "无效的章节ID"))
		return
	}

	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	if err := h.bookService.RestoreChapterFromRecycleBin(c, uint(id), userID); err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, gin.H{"message": "章节已成功恢复"})
}

// BatchRestore 批量恢复
func (h *BookRecycleHandler) BatchRestore(c *gin.Context) {
	var req bookApp.BatchRestoreRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.Error(err)
		return
	}

	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	restoredIDs, failures, err := h.bookService.BatchRestoreFromRecycleBin(c, &req, userID)
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, gin.H{
		"message":      "批量恢复操作已完成",
		"restored_ids": restoredIDs,
		"failures":     failures,
	})
}

// PermanentlyDelete 永久删除
func (h *BookRecycleHandler) PermanentlyDelete(c *gin.Context) {
	var req bookApp.PermanentDeleteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.Error(err)
		return
	}

	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	deletedIDs, failures, err := h.bookService.PermanentlyDeleteFromRecycleBin(c, &req, userID)
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, gin.H{
		"message":     "永久删除操作已完成",
		"deleted_ids": deletedIDs,
		"failures":    failures,
	})
}

// ClearRecycleBin 清空回收站
func (h *BookRecycleHandler) ClearRecycleBin(c *gin.Context) {
	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	if err := h.bookService.ClearRecycleBin(c, userID); err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, gin.H{"message": "回收站已清空"})
}
